/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package exatrez.stripes.action;

import able.stripes.JSP;
import com.google.inject.Inject;
import exatrez.dao.DepartmentDAO;
import exatrez.dao.PenggunaDAO;
import exatrez.dao.ShipVisitCounterDAO;
import exatrez.dao.ShipVisitDAO;
import exatrez.dao.ShipVisitFileDAO;
import exatrez.manager.VisitManager;
import exatrez.model.InfoAudit;
import exatrez.model.ShipVisit;
import exatrez.model.ShipVisitCounter;
import exatrez.model.ShipVisitFile;
import exatrez.model.User;
import exatrez.stripes.BaseActionBean;
import exatrez.stripes.Configuration;
import exatrez.stripes.config.AuthRequired;
import exatrez.stripes.util.FileUtil;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.FileBean;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Mansur
 */
@UrlBinding("/shipVisit")
@AuthRequired
public class ShipVisitAction extends BaseActionBean {
    
    private static Logger LOG = LoggerFactory.getLogger(ShipVisitAction.class);
    private ShipVisit shipVisit;
    private ShipVisitFile shipVisitFile;
    private ShipVisitCounter shipVisitCounter;
    private List<ShipVisit> listShipVisit;
    private List<ShipVisit> listSearchStaff;
    private List<ShipVisitCounter> listCounter;
    private List<ShipVisitFile> listVisitFile;
    private String staffId;
    private String departmentId;
    private String currentYear = String.valueOf(new Date().getYear()+1900);
    private Integer counterId;
    private String visitId;
    private FileBean document;
    private Integer defaultCount = 0;
    private String pastYear;
    
    @Inject
    private VisitManager svManager;
    @Inject
    private ShipVisitDAO shipVisitDAO;
    @Inject
    private ShipVisitFileDAO shipVisitFileDAO;
    @Inject
    private ShipVisitCounterDAO shipVisitCounterDAO;
    @Inject
    private PenggunaDAO userDAO;
    @Inject
    private DepartmentDAO departmentDAO;
    @Inject
    Configuration conf;
    
    private static final String NEWVISIT = "visit/new_visit.jsp";
    private static final String LISTVISITSTAFF = "visit/list_visit_staff.jsp";
    private static final String SEARCHSTAFF = "visit/search_list_visit.jsp";
    private static final String SEARCHSTAFFDETAIL = "visit/search_list_visit_detail.jsp";
    private static final String EDITDOCUMENT = "visit/edit_doc.jsp";
    private static final String VIEWDOCUMENT = "visit/view_doc.jsp";
    private static final String SEARCHPASTVISIT = "visit/search_past_visit_staff.jsp";
    private static final String FOLDERNAME = "shipVisit";
    private String path;
    
//    standard contenttype
    private String forXlsx = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    private String forDocx = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
    private String forPptx = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
    private String forXls = "application/vnd.ms-excel";
    private String forDoc = "application/msword";
    private String forPpt = "application/vnd.ms-powerpoint";
    private String forPdf = "application/pdf";
    private String forVideoMov = "video/quicktime";
    private String forVideoMkv = "video/x-matroska";
    private String forVideoMp4 = "video/mp4";
    private String forVideoAvi = "video/x-msvideo";
    private String forVideoMpeg= "video/mpeg";
    private String forVideoWmv = "application/octet-stream";
    private String forVideoAsf = "video/x-ms-asf";
    private String forVideoFlv = "video/x-flv";
    private String forVideoRmvb= "application/vnd.rn-realmedia-vbr";
    private String forVideo3gp = "video/3gpp";
    
    
    @DefaultHandler
    public Resolution newVisit(){
        User user = getContext().getCurrentUser();
        LOG.debug("currentYear : "+currentYear);
        listCounter = svManager.getListCounter(user, currentYear, departmentId);
        this.checkListCounter(listCounter);
        for (ShipVisitCounter c : listCounter) {
            counterId = c.getSvCounterId();
        }
        return new JSP(NEWVISIT);
    }
    
    public Resolution saveVisit(){
        User user = getContext().getCurrentUser();
        LOG.debug("user.id :"+user.getUserId());
        
        InfoAudit ia = new InfoAudit();
        ia.setCreateDate(new Date());
        ia.setCreateId(user);
        ia.setUpdateDate(new Date());
        ia.setUpdateId(user);
        
        try{
            shipVisit.setDeleted("N");
            shipVisit.setUser(user);
            shipVisit.setInfoAudit(ia);

            LOG.info("counterId :"+counterId);
            shipVisitCounter = shipVisitCounterDAO.findById(counterId);

            LOG.info("shipVisitCounter.id :"+shipVisitCounter.getSvCounterId()+", shipVisitCounter.visited :"+shipVisitCounter.getVisited());
            shipVisitCounter.setVisited(shipVisitCounter.getVisited()+1);

            String result = svManager.saveOrUpdateVisit(shipVisit,shipVisitCounter);
            if(result.equals("success")){
                addSimpleMessage("Success");

    //            listShipVisit = svManager.getListVisited(user);
    //            LOG.debug("listShipVisit.size :"+listShipVisit.size());
                listCounter = svManager.getListCounter(user, currentYear, departmentId);
            }else{
                addSimpleError("Fail : Please see Administrator for more information.");
                listCounter = svManager.getListCounter(user, currentYear, departmentId);
            }
        }catch(Exception ex){
            LOG.error("Error :", ex.getMessage());
            addSimpleError("Fail : Please see Administrator for more information and suggestion.");
        }finally{
            shipVisit = new ShipVisit();
            LOG.info("finally :"+shipVisit.getLocation());
        }
        
//        return new JSP(NEWVISIT);
        return new RedirectResolution(ShipVisitAction.class,"newVisit");
    }
    
    public Resolution viewListVisit(){
        User user = getContext().getCurrentUser();
        LOG.info("user :"+user.getUserId());
        listShipVisit = svManager.getListVisited(user);
        LOG.debug("listShipVisit.size :"+listShipVisit.size());     
        listCounter = svManager.getListCounter(user, currentYear, departmentId);
        this.checkListCounter(listCounter);
        for (ShipVisitCounter c : listCounter) {
            counterId = c.getSvCounterId();
        }
        return new JSP(LISTVISITSTAFF);
    }
    
    public Resolution mainStaffVisit(){
        
        return new JSP(SEARCHSTAFF);
    }
    
    public Resolution searchStaffVisit(){
        User user = getContext().getCurrentUser();
        listCounter = svManager.getListCounter(null, currentYear, departmentId);
        LOG.debug("listCounter :"+listCounter.size());
        return new JSP(SEARCHSTAFF);
    }
    
    public Resolution searchStaffVisitDetail(){
        LOG.info("staffId :"+staffId);
        User user = userDAO.findById(staffId);
        listCounter = svManager.getListCounter(user, currentYear, departmentId);
        listShipVisit = svManager.getListVisited(user);
        return new JSP(SEARCHSTAFFDETAIL);
    }
    
    public Resolution deleteVisited(){
        User user = getContext().getCurrentUser();
        LOG.info("visitId :"+visitId);
        LOG.info("user.userId :"+user.getUserId());
        shipVisit = shipVisitDAO.findById(Integer.parseInt(visitId));
        
        InfoAudit ia = shipVisit.getInfoAudit();
        ia.setUpdateId(user);
        ia.setUpdateDate(new Date());        
        shipVisit.setInfoAudit(ia);
        
        listCounter = svManager.getListCounter(user, currentYear, departmentId);
        for (ShipVisitCounter c : listCounter) {
            counterId = c.getSvCounterId();
        }
        shipVisitCounter = shipVisitCounterDAO.findById(counterId);
        LOG.info("shipVisitCounter.ia.create :"+shipVisitCounter.getInfoAudit().getCreateId().getUserId());
        InfoAudit iac = shipVisitCounter.getInfoAudit();
        iac.setUpdateId(user);
        iac.setUpdateDate(new Date());
        shipVisitCounter.setInfoAudit(iac);
        
        shipVisitCounter.setVisited(shipVisitCounter.getVisited()-1);
        String result = svManager.deleteVisit(shipVisit, shipVisitCounter);
        if(result.equals("success")){
            addSimpleMessage("Record has been deleted successfully.");
        }else{
            addSimpleError("Got problem to delete record.");
        }
        return viewListVisit();
    }
    
    public Resolution editDocument(){
        visitId = getContext().getRequest().getParameter("idVisit");
        if(StringUtils.isNotBlank(visitId)){
            listVisitFile = svManager.getListFile(Integer.parseInt(visitId));
        }
        
        return new JSP(EDITDOCUMENT).addParameter("popup", true);
    }
    
    public Resolution saveDoc(){
        String documentPath = conf.getProperty("document.path");
        InfoAudit ia = new InfoAudit();
        LOG.info("documentPath :"+documentPath);
        
        shipVisit = shipVisitDAO.findById(Integer.parseInt(visitId));
        String path = documentPath + (documentPath.endsWith(File.separator) ? "" : File.separator) + FOLDERNAME + File.separator + shipVisit.getShipVisitId() + File.separator;
        String docPath = FOLDERNAME + File.separator + shipVisit.getShipVisitId() + File.separator;
        
        LOG.info("path :"+path);
        LOG.info("docPath :"+docPath);
        
        if(document != null){
                FileUtil fileUtil = new FileUtil(path);
                LOG.debug("fileUtil : pass");
                try{
                    String filename = fileUtil.saveFile(document.getFileName(), document.getInputStream(), document.getSize());
                    LOG.debug("filename : "+filename);
                    ShipVisitFile visitFile = new ShipVisitFile();
                    visitFile.setDeleted("N");
                    visitFile.setDocumentPath(docPath + document.getFileName());
                    visitFile.setTitle(document.getFileName());
                    visitFile.setShipVisit(shipVisit);
                    visitFile.setContentType(document.getContentType());
                    ia.setCreateDate(new Date());
                    ia.setCreateId(getContext().getCurrentUser());
                    visitFile.setInfoAudit(ia);
                    LOG.debug("file title :"+visitFile.getTitle());
                    String result = svManager.saveorUpdateVisitFile(visitFile);
                    if(result.equals("success"))
                        addSimpleMessage("File success uploaded.");
                    else
                        addSimpleError("File fail to upload. Please try again.");
                }catch (Exception ex) {
                    LOG.error("(shipVisitAction) error while saving file {}", ex.getCause().getMessage());
                    addSimpleError("File fail to upload. File not valid.");
                }
            }
        return new RedirectResolution(ShipVisitAction.class, "editDocument")
                .addParameter("idVisit", shipVisit.getShipVisitId());
        }
    
    public Resolution deleteFile(){
        visitId = getContext().getRequest().getParameter("idVisit");
        String fileId = getContext().getRequest().getParameter("idFile");
        
        if(StringUtils.isNotBlank(fileId)){
            shipVisitFile = shipVisitFileDAO.findById(Integer.parseInt(fileId));
            shipVisitFile.setDeleted("Y");
            
            InfoAudit ia = shipVisitFile.getInfoAudit();
            ia.setUpdateDate(new Date());
            ia.setUpdateId(getContext().getCurrentUser());
            shipVisitFile.setInfoAudit(ia);
            String result = svManager.saveorUpdateVisitFile(shipVisitFile);
            if(result.equals("success"))
                addSimpleMessage("File is successfully deleted.");
            else
                addSimpleError("Error to delete file.");
        }else{
            addSimpleError("ID File is not required. Please provide ID for file.");
        }
        
        return editDocument();
    }
    
    public Resolution viewDoc(){
        visitId = getContext().getRequest().getParameter("idVisit");
        if(StringUtils.isNotBlank(visitId)){
            listVisitFile = svManager.getListFile(Integer.parseInt(visitId));
        }
        return new JSP(VIEWDOCUMENT).addParameter("popup", true);
    }
    
    private void checkListCounter(List<ShipVisitCounter> list){        
        String result = null;
        User user = getContext().getCurrentUser();
        if(list.size() == 0){
            ShipVisitCounter visitCounter = new ShipVisitCounter();
            visitCounter.setUser(user);
            visitCounter.setVisited(defaultCount);
            visitCounter.setYear(currentYear);
            visitCounter.setTarget(departmentDAO.findById(user.getDepartment().getDepartmentId()).getTarget());
            
            InfoAudit ia = new InfoAudit();
            ia.setCreateId(user);
            ia.setCreateDate(new Date());
            visitCounter.setInfoAudit(ia);
            result = svManager.saveOrUpdateVisitCounter(visitCounter);
            LOG.debug("(checkListCounter)result new visitCounter :"+result);
            listCounter = svManager.getListCounter(user, currentYear, departmentId);
        }else{
            if(list.get(0).getTarget().compareTo(user.getDepartment().getTarget()) == 0){
                result = "bingo.. the value is pair";
                LOG.debug("(checkListCounter)result visitCounter :"+result);
            }else{
                shipVisitCounter = shipVisitCounterDAO.findById(listCounter.get(0).getSvCounterId());
                shipVisitCounter.setTarget(user.getDepartment().getTarget());
                 InfoAudit iaU = shipVisitCounter.getInfoAudit();
                 iaU.setUpdateDate(new Date());
                 iaU.setUpdateId(user);
                result = svManager.saveOrUpdateVisitCounter(shipVisitCounter);
                LOG.debug("(checkListCounter)result update visitCounter :"+result);
                listCounter = svManager.getListCounter(user, currentYear, departmentId);
            }
        }
    }
    
    public Resolution searchPastVisitStaf(){
        User user = getContext().getCurrentUser();
        listCounter = new ArrayList<ShipVisitCounter>();
        listShipVisit = new ArrayList<ShipVisit>();
        LOG.debug("(searchPastVisitStaf) start");
        if(!StringUtils.isEmpty(pastYear)){
            LOG.debug("(searchPastVisitStaf)pastYear :"+pastYear);
            listCounter = svManager.getListPastVisitCounterStaff(user, pastYear);
            LOG.debug("(searchPastVisitStaf)listCounter.size :"+listCounter.size());            
            listShipVisit = svManager.getListPastVisitStaff(user, pastYear);
            LOG.debug("(searchPastVisitStaf)listShipVisit.size :"+listShipVisit.size());            
        }
        return new JSP(SEARCHPASTVISIT);
    }
    
    public Resolution refreshPage(){
        return new RedirectResolution(ShipVisitAction.class,"viewListVisit");
    }

    public ShipVisit getShipVisit() {
        return shipVisit;
    }

    public void setShipVisit(ShipVisit shipVisit) {
        this.shipVisit = shipVisit;
    }

    public ShipVisitFile getShipVisitFile() {
        return shipVisitFile;
    }

    public void setShipVisitFile(ShipVisitFile shipVisitFile) {
        this.shipVisitFile = shipVisitFile;
    }

    public List<ShipVisit> getListShipVisit() {
        return listShipVisit;
    }

    public void setListShipVisit(List<ShipVisit> listShipVisit) {
        this.listShipVisit = listShipVisit;
    }

    public List<ShipVisit> getListSearchStaff() {
        return listSearchStaff;
    }

    public void setListSearchStaff(List<ShipVisit> listSearchStaff) {
        this.listSearchStaff = listSearchStaff;
    }

    public String getDepartmentId() {
        return departmentId;
    }

    public void setDepartmentId(String departmentId) {
        this.departmentId = departmentId;
    }

    public List<ShipVisitCounter> getListCounter() {
        return listCounter;
    }

    public void setListCounter(List<ShipVisitCounter> listCounter) {
        this.listCounter = listCounter;
    }

    public String getCurrentYear() {
        return currentYear;
    }

    public void setCurrentYear(String currentYear) {
        this.currentYear = currentYear;
    }

    public ShipVisitCounter getShipVisitCounter() {
        return shipVisitCounter;
    }

    public void setShipVisitCounter(ShipVisitCounter shipVisitCounter) {
        this.shipVisitCounter = shipVisitCounter;
    }

    public Integer getCounterId() {
        return counterId;
    }

    public void setCounterId(Integer counterId) {
        this.counterId = counterId;
    }

    public String getStaffId() {
        return staffId;
    }

    public void setStaffId(String staffId) {
        this.staffId = staffId;
    }

    public String getVisitId() {
        return visitId;
    }

    public void setVisitId(String visitId) {
        this.visitId = visitId;
    }

    public List<ShipVisitFile> getListVisitFile() {
        return listVisitFile;
    }

    public void setListVisitFile(List<ShipVisitFile> listVisitFile) {
        this.listVisitFile = listVisitFile;
    }

    public FileBean getDocument() {
        return document;
    }

    public void setDocument(FileBean document) {
        this.document = document;
    }

    public Integer getDefaultCount() {
        return defaultCount;
    }

    public void setDefaultCount(Integer defaultCount) {
        this.defaultCount = defaultCount;
    }

    public String getForXlsx() {
        return forXlsx;
    }

    public void setForXlsx(String forXlsx) {
        this.forXlsx = forXlsx;
    }

    public String getForDocx() {
        return forDocx;
    }

    public void setForDocx(String forDocx) {
        this.forDocx = forDocx;
    }

    public String getForPptx() {
        return forPptx;
    }

    public void setForPptx(String forPptx) {
        this.forPptx = forPptx;
    }

    public String getForXls() {
        return forXls;
    }

    public void setForXls(String forXls) {
        this.forXls = forXls;
    }

    public String getForDoc() {
        return forDoc;
    }

    public void setForDoc(String forDoc) {
        this.forDoc = forDoc;
    }

    public String getForPpt() {
        return forPpt;
    }

    public void setForPpt(String forPpt) {
        this.forPpt = forPpt;
    }

    public String getForPdf() {
        return forPdf;
    }

    public void setForPdf(String forPdf) {
        this.forPdf = forPdf;
    }

    public String getForVideoMov() {
        return forVideoMov;
    }

    public void setForVideoMov(String forVideoMov) {
        this.forVideoMov = forVideoMov;
    }

    public String getForVideoMkv() {
        return forVideoMkv;
    }

    public void setForVideoMkv(String forVideoMkv) {
        this.forVideoMkv = forVideoMkv;
    }

    public String getForVideoMp4() {
        return forVideoMp4;
    }

    public void setForVideoMp4(String forVideoMp4) {
        this.forVideoMp4 = forVideoMp4;
    }

    public String getForVideoAvi() {
        return forVideoAvi;
    }

    public void setForVideoAvi(String forVideoAvi) {
        this.forVideoAvi = forVideoAvi;
    }

    public String getForVideoMpeg() {
        return forVideoMpeg;
    }

    public void setForVideoMpeg(String forVideoMpeg) {
        this.forVideoMpeg = forVideoMpeg;
    }

    public String getForVideoWmv() {
        return forVideoWmv;
    }

    public void setForVideoWmv(String forVideoWmv) {
        this.forVideoWmv = forVideoWmv;
    }

    public String getForVideoAsf() {
        return forVideoAsf;
    }

    public void setForVideoAsf(String forVideoAsf) {
        this.forVideoAsf = forVideoAsf;
    }

    public String getForVideoFlv() {
        return forVideoFlv;
    }

    public void setForVideoFlv(String forVideoFlv) {
        this.forVideoFlv = forVideoFlv;
    }

    public String getForVideoRmvb() {
        return forVideoRmvb;
    }

    public void setForVideoRmvb(String forVideoRmvb) {
        this.forVideoRmvb = forVideoRmvb;
    }

    public String getForVideo3gp() {
        return forVideo3gp;
    }

    public void setForVideo3gp(String forVideo3gp) {
        this.forVideo3gp = forVideo3gp;
    }

    public String getPath() {
//        String documentPath = conf.getProperty("document.path");
//        path = documentPath + (documentPath.endsWith(File.separator) ? "" : File.separator);
        path = conf.getProperty("document.path");
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getPastYear() {
        return pastYear;
    }

    public void setPastYear(String pastYear) {
        this.pastYear = pastYear;
    }
}
